
using SimpleFramework;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Events;

namespace SimpleFramework
{
    public class HotupReplaceState : HotupState
    {
        private int m_Index;
        private List<string> m_Filelist = new List<string>();
        public UnityEvent<int, int> onProgress = new UnityEvent<int, int>();

        public HotupReplaceState(HotupContext context) : base(context)
        {
        }

        public override void OnEnter()
        {
            Debug.Log("ReplaceTask.Start");
            var files = Directory.GetFiles(PathUtils.DownloadTempPath, "*." + HotupConst.FILE_EXTENSION);
            if (files.Length > 0)
            {
                m_Index = 0;
                m_Filelist.Clear();
                m_Filelist.AddRange(files);
                this.onProgress.Invoke(m_Index, m_Filelist.Count);
            }
            else
            {
                HotupSystem.Instance.Change(HotupStateId.Check);
            }
        }

        public override void OnUpdate()
        {
            if (m_Index < m_Filelist.Count)
            {
                var srcPath = m_Filelist[m_Index++];
                var srcName = Path.GetFileName(srcPath);
                var dstPath = PathUtils.GetDownloadRescPath(srcName);
                HotupUtils.Move(srcPath, dstPath, true);
                this.onProgress.Invoke(m_Index, m_Filelist.Count);
            }
            else
            {
                var filePath = PathUtils.GetDownloadTempPath(HotupConst.VERSION_NAME);
                if (File.Exists(filePath))
                {
                    var srcName = Path.GetFileName(filePath);
                    var dstPath = PathUtils.GetDownloadRescPath(srcName);
                    HotupUtils.Move(filePath, dstPath);
                }
                HotupSystem.Instance.Change(HotupStateId.Restart);
            }
        }

        public override void OnExit()
        {

        }
    }
}